package currency;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import NET.webserviceX.www.Currency;
import NET.webserviceX.www.CurrencyConvertorSoapProxy;

/**
 * Servlet implementation class CurrencyConvertor
 */
@WebServlet("/CurrencyConvertor")
public class CurrencyConvertor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private CurrencyConvertorSoapProxy currencyConvertor;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CurrencyConvertor() {
		super();
		currencyConvertor = new CurrencyConvertorSoapProxy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String valueParam = request.getParameter("value");
		double value = 0;
		try {
			value = Double.parseDouble(valueParam);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		String fromCurrencyCode = request.getParameter("fromCode");
		String toCurrencyCode = request.getParameter("toCode");
		
		double totalAmount = convert(value, fromCurrencyCode, toCurrencyCode);
		
		PrintWriter writer = response.getWriter();
		writer.write("" + totalAmount);
		writer.flush();
		writer.close();
	}

	private double convert(double value, String fromCurrencyCode,
			String toCurrencyCode) {
		Currency fromCurrency = Currency.fromString(fromCurrencyCode);
		Currency toCurrency = Currency.fromString(toCurrencyCode);

		double rate = 0;
		try {
			rate = currencyConvertor.conversionRate(fromCurrency, toCurrency);
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		double totalAmount = value * rate;
		return totalAmount;
	}

}
